package com.jinzhi.jzweb.controller;


import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.jinzhi.common.annotation.Log;
import com.jinzhi.common.base.BaseController;
import com.jinzhi.common.service.DictService;
import com.jinzhi.common.utils.Result;
import com.jinzhi.jzweb.domain.*;
import com.jinzhi.jzweb.service.*;
import com.jinzhi.jzweb.utils.IdCardUtil;
import com.jinzhi.sys.domain.UserDO;
import com.jinzhi.sys.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 *
 * <pre>
 * 课程表
 * </pre>
 * <small> 2020-02-24 21:00:12 | lance</small>
 */
@Controller
@RequestMapping("/jzweb/courses")
public class CoursesController extends BaseController {
	@Autowired
	private CoursesService coursesService;
	@Autowired
	private UserService userService;
	@Autowired
	private OrganizationNewsService organizationNewsService;
	@Autowired
	private OrganizationRolesService organizationRolesService;
	@Autowired
	private CertificateProfileService certificateProfileService;
	@Autowired
	private ExpertsService expertsService;
	@Autowired
	private DictService dictService;
    @Autowired
    private CoursesClassService coursesClassService;
    @Autowired
    private ClassesService classesService;

	@GetMapping()
	@RequiresPermissions("jzweb:courses:courses")
	String Courses(){
		return "jzweb/courses/courses";
	}

	@ResponseBody
	@GetMapping("/list")
	@RequiresPermissions("jzweb:courses:courses")
	public Result<Page<CoursesDO>> list(HttpServletRequest req, CoursesDO coursesDTO){
		Wrapper<CoursesDO> wrapper = new EntityWrapper<CoursesDO>().orderBy("id", false);
		if (coursesDTO.getState() != null){
			wrapper.eq("state",coursesDTO.getState());
		}
		if (coursesDTO.getName() != null){
			wrapper.like("name",coursesDTO.getName());
		}
		if (org.apache.commons.lang3.StringUtils.isNotBlank(coursesDTO.getProfileName())){
			Wrapper<CertificateProfileDO> cerWrapper = new EntityWrapper<CertificateProfileDO>().like("name",coursesDTO.getProfileName());
			List<CertificateProfileDO>  certificateProfileDOS = certificateProfileService.selectList(cerWrapper);
			String str = "";
			for (CertificateProfileDO certificateProfileDO : certificateProfileDOS){
				str = str + certificateProfileDO.getId() + ",";
			}
			wrapper.and();
			if(org.apache.commons.lang3.StringUtils.isNotBlank(str)){
				wrapper.in("profile_id",str.substring(0,str.length()-1));
			}else{
				wrapper.eq("profile_id",null);
			}
		}
		//查询用户角色
		String roleName = getRoleNames();
		if (!roleName.contains("超级用户角色")) {
			Object orgId = req.getSession().getAttribute("orgId");
			if (orgId != null){
				wrapper.eq("org_id",orgId);
			}else {
				wrapper.eq("org_id",this.getUser().getOrgId());
			}

			if(roleName.contains("讲师") && !roleName.contains("培训机构")){
				wrapper.eq("user_id",this.getUserId());
			}
		}else{
			if (org.apache.commons.lang3.StringUtils.isNotBlank(coursesDTO.getOrgName())){
				Wrapper<OrganizationNewsDO> orWrapper = new EntityWrapper<OrganizationNewsDO>().like("name",coursesDTO.getOrgName());
				List<OrganizationNewsDO>  organizationNewsDOS = organizationNewsService.selectList(orWrapper);
				String str = "";
				for (OrganizationNewsDO organizationNewsDO : organizationNewsDOS){
					str = str + organizationNewsDO.getId() + ",";
				}
				wrapper.and();
				if(StringUtils.isNotBlank(str)){
					wrapper.in("org_id",str.substring(0,str.length()-1));
				}else{
					wrapper.eq("org_id",null);
				}
			}
		}

		if (StringUtils.isNotBlank(coursesDTO.getUserName())){
			Wrapper<UserDO> uWrapper = new EntityWrapper<UserDO>().like("name",coursesDTO.getUserName());
			List<UserDO>  userDOS = userService.selectList(uWrapper);
			String str = "";
			for (UserDO userDO : userDOS){
				str = str + userDO.getId() + ",";
			}
			wrapper.and();
			if(StringUtils.isNotBlank(str)){
				wrapper.in("user_id",str.substring(0,str.length()-1));
			}else{
				wrapper.eq("user_id",null);
			}
		}

		Page<CoursesDO> page = coursesService.selectPage(getPage(CoursesDO.class), wrapper);
		List list = new ArrayList();
		for (int i = 0; i < page.getRecords().size(); i++) {
			CoursesDO obj = (CoursesDO) page.getRecords().get(i);
			if (obj.getUserId() != null){
				UserDO userDO = userService.selectById(obj.getUserId());
				if (userDO != null) {
					obj.setUserName(userDO.getName());
				}
			}
			if (obj.getOrgId() != null){
				OrganizationNewsDO organizationNewsDO = organizationNewsService.selectById(obj.getOrgId());
				if (organizationNewsDO != null) {
					obj.setOrgName(organizationNewsDO.getName());
				}
			}
			if (obj.getProfileId() != null){
				CertificateProfileDO certificateProfileDO = certificateProfileService.selectById(obj.getProfileId());
				if (certificateProfileDO != null) {
					obj.setProfileName(certificateProfileDO.getName());
				}
			}
			if (obj.getCreaterId() != null){
				UserDO userDO = userService.selectById(obj.getCreaterId());
				if (userDO != null) {
					obj.setCreaterName(userDO.getUsername());
				}
			}
			if (obj.getUpdaterId() != null){
				UserDO userDO = userService.selectById(obj.getUpdaterId());
				if (userDO != null) {
					obj.setUpdateName(userDO.getUsername());
				}
			}
			list.add(obj);
		}
		page.setRecords(list);
		return Result.ok(page);
	}

	@GetMapping("/add")
	@RequiresPermissions("jzweb:courses:add")
	String add(Model model){
		Map<String, String> map = new HashMap<>();
		map.put("name", "课程通过条件");
		map.put("type", "course_pass");
		List<Map> maps = dictService.selTypeNameVue(map);
		model.addAttribute("adoptFactors",maps);
		String roleName = getRoleNames();
		if (!roleName.contains("超级用户角色")) {
			List<Map<Object,Object>> list = new ArrayList<>();
			Map<Object,Object> map1 = new HashMap();
			map1.put("id",this.getUser().getOrgId());
			OrganizationNewsDO organizationNewsDO = organizationNewsService.selectById(this.getUser().getOrgId());
			if(organizationNewsDO != null){
				map1.put("name",organizationNewsDO.getName());
			}else{
				map1.put("name",this.getUser().getOrgName());
			}
			list.add(map1);
			model.addAttribute("orgNews",list);
		} else {
			model.addAttribute("orgNews",organizationRolesService.selByRoleType(0));
		}
		return "jzweb/courses/add";
	}

	@GetMapping("/edit/{id}")
	@RequiresPermissions("jzweb:courses:edit")
	String edit(@PathVariable("id") Long id,Model model){
		Map<String, String> map = new HashMap<>();
		map.put("name", "课程通过条件");
		map.put("type", "course_pass");
		List<Map> maps = dictService.selTypeNameVue(map);
		model.addAttribute("adoptFactors",maps);
		CoursesDO courses = coursesService.selectById(id);
		model.addAttribute("courses", courses);
		String roleName = getRoleNames();
		if (!roleName.contains("超级用户角色")) {
			List<Map<Object,Object>> list = new ArrayList<>();
			Map<Object,Object> map1 = new HashMap();
			map1.put("id",this.getUser().getOrgId());
			OrganizationNewsDO organizationNewsDO = organizationNewsService.selectById(this.getUser().getOrgId());
			if(organizationNewsDO != null){
				map1.put("name",organizationNewsDO.getName());
			}else{
				map1.put("name",this.getUser().getOrgName());
			}
			list.add(map1);
			model.addAttribute("orgNews",list);
		} else {
			model.addAttribute("orgNews",organizationRolesService.selByRoleType(0));
		}
		return "jzweb/courses/edit";
	}

	@GetMapping("/info/{id}")
	@RequiresPermissions("jzweb:courses:courses")
	String info(@PathVariable("id") Long id, Model model) {
		CoursesDO courses = coursesService.selectById(id);
		//创建用户名
		if (courses.getCreaterId() != null) {
			UserDO userDO = userService.selectById(courses.getCreaterId());
			if (userDO != null) {
				courses.setCreaterName(userDO.getUsername());
			}
		}
		//讲师姓名
		if (courses.getUserId() != null) {
			UserDO userDO = userService.selectById(courses.getUserId());
			if (userDO != null) {
				courses.setUserName(userDO.getUsername());
			}
		}
		//审核用户名
		if (courses.getUpdaterId() != null) {
			UserDO userDO = userService.selectById(courses.getUpdaterId());
			if (userDO != null) {
				courses.setUpdateName(userDO.getUsername());
			}
		}
		//机构名称
		if (courses.getOrgId() != null){
			OrganizationNewsDO organizationNewsDO = organizationNewsService.selectById(courses.getOrgId());
			if (organizationNewsDO != null) {
				courses.setOrgName(organizationNewsDO.getName());
			}
		}
		//证书名称
		if (courses.getProfileId() != null) {
			CertificateProfileDO certificateProfileDO = certificateProfileService.selectById(courses.getProfileId());
			if (certificateProfileDO != null) {
				courses.setProfileName(certificateProfileDO.getName());
			}
		}
		model.addAttribute("courses", courses);
		return "jzweb/courses/info";
	}

	@Log("添加课程表")
	@ResponseBody
	@PostMapping("/save")
	@RequiresPermissions("jzweb:courses:add")
	public Result<String> save( CoursesDO courses){
		//考核期数(从课程中截取)
//        String exaNumber = "01";
//        if(courses.getName().length() > 4){
//            exaNumber = courses.getName().substring(courses.getName().length() - 4, courses.getName().length() - 2);
//        }
		//判断是否为数字
//		if (!IdCardUtil.isNumeric(exaNumber)) {
//			return Result.fail("课程名称" + courses.getName() + "填写错误，期数请填写阿拉伯数字，例如：01或11;");
//		}
		courses.setCreaterId(this.getUserId());
		courses.setUpdaterId(this.getUserId());
		coursesService.insert(courses);
		return Result.ok();
	}

	@Log("修改课程表")
	@ResponseBody
	@RequestMapping("/update")
	@RequiresPermissions("jzweb:courses:edit")
	public Result<String>  update( CoursesDO courses){
		//考核期数(从课程中截取)
//        String exaNumber = "01";
//	    if(courses.getName().length() > 4){
//            exaNumber = courses.getName().substring(courses.getName().length() - 4, courses.getName().length() - 2);
//        }

		//判断是否为数字
//		if (!IdCardUtil.isNumeric(exaNumber)) {
//			return Result.fail("课程名称" + courses.getName() + "填写错误，期数请填写阿拉伯数字，例如：01或11;");
//		}
		courses.setUpdaterId(this.getUserId());
		boolean update = coursesService.updateById(courses);
		return update ? Result.ok() : Result.fail();
	}

	@Log("删除课程表")
	@PostMapping( "/remove")
	@ResponseBody
	@RequiresPermissions("jzweb:courses:remove")
	public Result<String>  remove( Long id){
		coursesService.deleteById(id);
		return Result.ok();
	}

	@Log("批量删除课程表")
	@PostMapping( "/batchRemove")
	@ResponseBody
	@RequiresPermissions("jzweb:courses:batchRemove")
	public Result<String>  remove(@RequestParam("ids[]") Long[] ids){
		coursesService.deleteBatchIds(Arrays.asList(ids));
		return Result.ok();
	}

	@Log("课程上架")
	@PostMapping( "/batchUpper")
	@ResponseBody
	@RequiresPermissions("jzweb:courses:batchRemove")
	public Result<String>  batchUpper(@RequestParam("ids[]") Long[] ids){
		List<CoursesDO> coursesDOS = new ArrayList<>();
		for(Long id : ids){
			CoursesDO coursesDO = coursesService.selectById(id);
			coursesDO.setState(0);
			coursesDO.setUpdateDate(new Date());
			coursesDOS.add(coursesDO);
		}
		boolean bbc = coursesService.updateBatchById(coursesDOS,coursesDOS.size());
		return bbc ? Result.ok() : Result.fail();
	}

	@Log("课程下架")
	@PostMapping( "/batchLower")
	@ResponseBody
	@RequiresPermissions("jzweb:courses:batchRemove")
	public Result<String>  batchLower(@RequestParam("ids[]") Long[] ids){
		List<CoursesDO> coursesDOS = new ArrayList<>();
		for(Long id : ids){
			CoursesDO coursesDO = coursesService.selectById(id);
			coursesDO.setState(1);
			coursesDO.setUpdateDate(new Date());
			coursesDOS.add(coursesDO);
		}
		boolean bbc = coursesService.updateBatchById(coursesDOS,coursesDOS.size());
		return bbc ? Result.ok() : Result.fail();
	}

	@Log("机构对应的证书信息")
	@GetMapping( "/selPros")
	@ResponseBody
	public Result<?> selPros(String orgIds) {
		if(StringUtils.isNotBlank(orgIds)){
			List<Map> maps = new ArrayList<>();
			Map map1 = new HashMap();
			map1.put("orgId",Long.parseLong(orgIds));
			map1.put("roleType",0);
			String proName = organizationRolesService.selByIdProName(map1);
			if(StringUtils.isNotBlank(proName)){
				String[] pron = proName.split(",");
				for(String p : pron){
					if(StringUtils.isNotBlank(p)){
						Map map = new HashMap();
						CertificateProfileDO certificateProfileDO = certificateProfileService.selectById(Long.parseLong(p));
						if(certificateProfileDO != null){
							map.put("id",certificateProfileDO.getId());
							map.put("name",certificateProfileDO.getName());
							maps.add(map);
						}
					}
				}
			}
			return Result.ok(maps);
		}
		return Result.ok();
	}

    @Log("机构对应证书的讲师信息")
    @GetMapping( "/selTeacher")
    @ResponseBody
    public Result<?> selTeacher(String orgIds,String cprofileIds) {
        Map map = new HashMap();

        //查询用户角色
        String roleName = getRoleNames();
        if (!roleName.contains("超级用户角色")) {
            //讲师
            if(roleName.contains("讲师") && !roleName.contains("培训机构")){
                map.put("userId",this.getUserId());
            }
            if(StringUtils.isNotBlank(orgIds)){
                map.put("orgId",Long.parseLong(orgIds));
            }else{
                map.put("orgId",getUser().getOrgId());
            }
        }else{
            if(StringUtils.isNotBlank(orgIds)){
                map.put("orgId",Long.parseLong(orgIds));
            }else{
                map.put("orgId",null);
            }
        }

        if(StringUtils.isNotBlank(cprofileIds)){
            map.put("profileId",Long.parseLong(cprofileIds));
        }

        List<Map> maps= expertsService.selTeacher(map);
        return Result.ok(maps);
    }

    @Log("机构对应证书的课程信息")
    @GetMapping( "/selCoureses")
    @ResponseBody
    public Result<?> selCoureses(String orgIds,String cprofileIds,String teacherIds) {
        Wrapper<CoursesDO> CoursesWrapper = new EntityWrapper<CoursesDO>().orderBy("id", false);
        Map map = new HashMap();

        //查询用户角色
        String roleName = getRoleNames();
        if (!roleName.contains("超级用户角色")) {
            //讲师
            if(roleName.contains("讲师") && !roleName.contains("培训机构")){
                CoursesWrapper.eq("user_id",this.getUserId());
            }
            if(StringUtils.isNotBlank(orgIds)){
                CoursesWrapper.eq("org_id",Long.parseLong(orgIds));
            }else{
                CoursesWrapper.eq("org_id",getUser().getOrgId());
            }
        }else{
            if(StringUtils.isNotBlank(orgIds)){
                CoursesWrapper.eq("org_id",Long.parseLong(orgIds));
            }else{
                CoursesWrapper.eq("org_id",null);
            }
        }

        if(StringUtils.isNotBlank(cprofileIds)){
            CoursesWrapper.eq("profile_id",Long.parseLong(cprofileIds));
        }
        List<Map> maps= new ArrayList<>();
        List<CoursesDO> CoursesDOs = coursesService.selectList(CoursesWrapper);
        if(CoursesDOs.size()>0) {
            for (CoursesDO coursesDO : CoursesDOs) {
                Map newMap = new HashMap();
                newMap.put("id", coursesDO.getId());
                newMap.put("name", coursesDO.getName());
                maps.add(newMap);
            }
        }
        return Result.ok(maps);
    }

    /**
	 * 对应机构下的课程数据接口
	 */
	@Log("对应机构下的课程数据接口")
	@GetMapping( "/course")
	@ResponseBody
	Result<?> course(){
		UserDO user = this.getUser();
		//查询用户角色
		String roleName = getRoleNames();
		List<CoursesDO> coursesList;
		if (!roleName.contains("超级用户角色")) {
			//讲师
			if(roleName.contains("讲师") && !roleName.contains("培训机构")){
				coursesList = coursesService.findByKv("org_id" , user.getOrgId() ,"state" , 0,"user_id",user.getId());
			}else{
				coursesList = coursesService.findByKv("org_id" , user.getOrgId() ,"state" , 0);
			}
		}else{
			coursesList = coursesService.findByKv("state" , 0);
		}

		return Result.ok(coursesList);
	}

    @Log("课程和老师对应的班级信息")
    @GetMapping( "/selCouresesClasses")
    @ResponseBody
    public Result<?> selCouresesClasses(String coursesIds) {
        Wrapper<CoursesClassDO> CoursesClassWrapper = new EntityWrapper<CoursesClassDO>().orderBy("id", false);
        Map map = new HashMap();

        //查询用户角色
        String roleName = getRoleNames();
        if (!roleName.contains("超级用户角色")) {
            //讲师
            if(roleName.contains("讲师") && !roleName.contains("培训机构")){
                CoursesClassWrapper.eq("create_user_id",this.getUserId());
            }
        }

        if(StringUtils.isNotBlank(coursesIds)){
            CoursesClassWrapper.eq("courses_id",Long.parseLong(coursesIds));
        }
        List<Map> maps= new ArrayList<>();
        List<CoursesClassDO> coursesClassDOS = coursesClassService.selectList(CoursesClassWrapper);
        if(coursesClassDOS.size()>0) {
            for (CoursesClassDO coursesClassDO : coursesClassDOS) {
                Map newMap = new HashMap();
                newMap.put("id", coursesClassDO.getClassId());
                StudentClassesDO studentClassesDO = this.classesService.selectById(coursesClassDO.getClassId());
                if(studentClassesDO!=null && studentClassesDO.getName()!=null) {
                    newMap.put("name", studentClassesDO.getName());
                }else {
                    newMap.put("name", "");
                }
                maps.add(newMap);
            }
        }
        return Result.ok(maps);
    }

}
